package model

import (
	"gorm.io/gorm"
	"smart-health-platforms/config"
	"time"
)

/*
站内信消息表
*/
type Message struct {
	gorm.Model
	SenderID   int64  `gorm:"type:int;not null;index;comment:发送者ID"`
	ReceiverID int64  `gorm:"type:int;not null;index;comment:接收者ID"`
	Content    string `gorm:"type:text;not null;comment:消息内容"`
	Type       int    `gorm:"type:int;comment:'消息类型 1-系统消息 2-用户消息 3-订单消息'"`
	IsRead     int    `gorm:"type:int;default:0;comment:'是否已读 0-未读 1-已读'"`
	ReadTime   *time.Time
}

// 创建消息
func (m *Message) CreateMessage() error {
	return config.DB.Create(&m).Error
}

// 获取用户未读消息数量
func (m *Message) GetUnreadCount(userID int64) (int64, error) {
	var count int64
	err := config.DB.Model(&Message{}).Where("receiver_id = ? AND is_read = ?", userID, 0).Count(&count).Error
	return count, err
}

// 获取用户消息列表
func (m *Message) GetMessageList(userID int64, page, pageSize int) ([]*Message, error) {
	var messages []*Message
	offset := (page - 1) * pageSize
	err := config.DB.Model(&Message{}).Where("receiver_id = ?", userID).Order("created_at DESC").Offset(offset).Limit(pageSize).Find(&messages).Error
	return messages, err
}

// 标记消息为已读
func (m *Message) MarkAsRead(messageID int64, isRead int) error {
	now := time.Now()
	return config.DB.Model(&Message{}).Where("id = ? and is_read = ?", messageID, isRead).Updates(map[string]interface{}{
		"is_read":   1,
		"read_time": &now,
	}).Error
}
